<template>
  <view class="app-layout">
    <app-header :title="tit" />
    <view class="app-main">
      <view class="goods-container" @click.prevent='handleClickOutside'>
        <view class="" style=" flex: 1; overflow: hidden;">
          <scroll-view scroll-y="true" scroll-x="true" style="height: 100%">
            <view class="form-container">
              <u-form labelPosition="left" labelWidth="110px" :model="formData" ref="refFrom">
                <view class="info-tit"> 基本信息</view>
                <view class="form-con" style="padding-right:76px">
                  <uni-row :gutter="40">
                    <view style="display: flex;">
                      <uni-col :span="12">
                        <u-form-item label="权益名称" required>
                          <uni-easyinput :maxlength="10" clearable v-model="formData.spuId" placeholder="请输入"
                            :disabled="spuId">
                            <template #right>
                              <text class="suffix-num">{{ (formData.spuId || '').length }}/10</text>
                            </template>
                          </uni-easyinput>
                        </u-form-item>
                      </uni-col>
                      <uni-col :span="12">
                        <u-form-item label="权益状态" required>
                          <u-radio-group v-model="formData.isPublished">
                            <u-radio :customStyle="{ marginRight: '8px' }" label="启用" :name="1" />
                            <u-radio label="禁用" :name="0" />
                          </u-radio-group>
                        </u-form-item>
                      </uni-col>
                    </view>
                    <uni-col :span="12">
                      <u-form-item label="适用会员等级" required @click="addVIP('1')">
                        <uni-easyinput clearable v-model="formData.level" placeholder="请选择会员等级" :disabled="true"
                          :styles="{ disableColor: '#fff',color:'#333'}" placeholderStyle="color: #999">
                          <template #right>
                            <view class="suffix-num">
                              <u-icon name="arrow-down-fill" color="#8590B3"></u-icon>
                            </view>

                            <!-- <text class="suffix-num">{{ (formData.spuId || '').length }}/8</text> -->
                          </template>
                        </uni-easyinput>
                      </u-form-item>
                    </uni-col>
                    <uni-col :span="12">
                      <u-row>
                        <view class="flex-label">
                          <u-form-item label="权益排序" required>
                            <uni-easyinput placeholder="请输入" type="number" clearable
                              v-model="formData.sortOrder"></uni-easyinput>
                          </u-form-item>
                        </view>


                        <view class="direction-container">
                          <view class="item" ref="tooltipContainer">
                            <image src="@/static/imgs/icon.png" mode="" class="icon-con" @click.stop="toggleTooltip">
                            </image>
                            <view class="tooltip-box" :class="{ show: isTooltipShow }" ref="tooltipRef">
                              <view class="tooltip-content">当同一会员等级下存在多个会员权益时时，系统将根据预设规则自动排序，确定在点单小程序中权益的展示顺序。</view>
                              <view class="tooltip-arrow"></view>
                            </view>
                          </view>
                        </view>
                      </u-row>
                    </uni-col>
                    <uni-col :span="24">
                      <view class="special-formitem">
                        <u-form-item label="权益图标" required>
                          <uploadImage :initial-images="uploadedImagesOne" @upload-success="handleUpload"
                            @remove="handleRemove" />
                          <view style="color: #999999; font-size: 14px; margin-bottom: 4px">建议尺寸：200*200px，大小不超过3MB
                          </view>
                        </u-form-item>
                      </view>
                    </uni-col>
                  </uni-row>
                </view>
                <view class="info-tit"> 权益配置 </view>
                <view class="form-con" style="padding-right:23px">
                  <uni-row>
                    <uni-col :span="16">
                      <u-form-item label="权益类型" required>
                        <u-radio-group v-model="formData.equityType" @change="changeType">
                          <u-radio :customStyle="{ marginRight: '8px' }" label="介绍类" :name="1" />
                          <u-radio label="优惠券" :name="0" />
                        </u-radio-group>
                        <view class="" @click="handleCoupon" v-if="equityType">
                          <uni-easyinput clearable v-model="formData.couponName" placeholder="请选择优惠券" :disabled="true"
                            :styles="{ disableColor: '#fff',color:'#333'}" placeholderStyle="color: #999">
                            <template #right>
                              <view class="suffix-num">
                                <u-icon name="arrow-down-fill" color="#8590B3"></u-icon>
                              </view>

                              <!-- <text class="suffix-num">{{ (formData.spuId || '').length }}/8</text> -->
                            </template>
                          </uni-easyinput>
                        </view>
                      </u-form-item>
                    </uni-col>
                    <uni-col :span="24" v-if="equityType">
                      <u-form-item label="发放方式" required>
                        <u-radio-group v-model="formData.method">
                          <u-radio :customStyle="{ marginRight: '8px' }" label="手动领取" :name="1" />
                          <u-radio label="自动发放" :name="0" />
                        </u-radio-group>
                      </u-form-item>
                    </uni-col>
                    <uni-col :span="24" v-if="equityType">
                      <u-form-item label="发放限制" required>
                        <view style="display: flex;flex:1;gap:10px">
                          <view class="">
                            <u-radio-group v-model="formData.restriction">
                              <u-radio :customStyle="{ marginRight: '8px' }" label="仅一次" :name="0" />
                              <u-radio :customStyle="{ marginRight: '8px' }" label="每日" :name="1" />
                              <u-radio :customStyle="{ marginRight: '8px' }" label="每周" :name="2" />
                              <u-radio :customStyle="{ marginRight: '8px' }" label="每月" :name="3" />
                              <u-radio label="每年" :name="4" />
                            </u-radio-group>
                          </view>
                          <view style="flex:2">
                            <uni-datetime-picker v-model="formData.range" type="daterange" @maskClick="maskClick"
                              @change="handleTime" />
                          </view>
                          <view style="flex:1.5;display: flex;align-items: center;">
                            <text style="font-weight: 400;font-size: 14px;color: #333333;margin-right:10px">发放</text>
                            <uni-easyinput placeholder="请输入发放次数" :maxlength="20" type="number" clearable
                              v-model="formData.productionTime">
                              <template #right>
                                <text class="suffix-txt">次</text>
                              </template>
                            </uni-easyinput>
                          </view>
                        </view>
                      </u-form-item>
                    </uni-col>
                  </uni-row>

                </view>
                <view class="info-tit"> 权益说明</view>
                <view class="form-con" style="padding-right:76px">
                  <uni-row>
                    <uni-col :span="24">
                      <u-row>
                        <view class="flex-label">
                          <u-form-item label="权益描述" required>
                            <u-textarea v-model="formData.description" :placeholder="'请输入'" :maxlength="200" :rows="5"
                              :autosize="true" count></u-textarea>

                          </u-form-item>
                        </view>


                        <view class="direction-container">
                          <view class="item">
                            <image src="@/static/imgs/icon.png" mode="" class="icon-con" @click.stop="toggleTooltips">
                            </image>
                            <view class="tooltip-box" :class="{ show: isTooltipShows }" ref="tooltipRef">
                              <view class="tooltip-content">用于在点单小程序向用户展示权益详细信息</view>
                              <view class="tooltip-arrow"></view>
                            </view>
                          </view>
                        </view>
                      </u-row>
                    </uni-col>
                    <uni-col :span="24">
                      <u-form-item label="权益备注">
                        <u-textarea v-model="formData.description" :placeholder="'请输入'" :maxlength="200" :rows="5"
                          :autosize="true" count></u-textarea>

                      </u-form-item>
                    </uni-col>
                  </uni-row>
                </view>
              </u-form>
            </view>
          </scroll-view>
        </view>
        <view class="submit_btncon">
          <view style="display: flex; margin: auto">
            <button class="submit_close" @click="close">取消</button>
            <button class="submit_btn" @click="submit">确认</button>
          </view>
        </view>
        <addPopup v-if="showPopup" :showPopup="showPopup" :titPopup="titPopup" @cancelPopup="cancelPopup"
          @surePopup="surePopup" :listPopup="listPopup" :valuePopup="valuePopup" />
      </view>

    </view>
  </view>
</template>
<script setup>
  import {
    ref,
    watch,
    nextTick,
    computed,
    onMounted,
    onUnmounted
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    getTreeCategory,
    updateSassCategoryById,
    addSassCategory,
    getAttributeDefinitions,
    getAddonOptions,
    addSassSpecs,
    findSpecsList,
    addProducts,
    updateProducts,
    getBySpuId
  } from '@/requests/apis/products'
  import {
    uploadImgApi
  } from '@/requests/apis/user'
  import
  addPopup
  from '@/components/addPopup/index.vue'
  import
  uploadImage
  from '@/components/upload-image/index.vue'
  const editorIns = ref(null)
  let spuId = ref()
  let tit = ref('新增会员权益')
  let show = ref(false)
  let showPopup = ref(false)
  let titPopup = ref()
  let listPopup = ref([])
  let vipLevelList = ref([])
  let valuePopup = ref()
  const checkboxValue1 = ref('')
  const checkboxValue2 = ref('')
  const radiovalue1 = ref(1)
  let equityType = ref(false) //权益类型
  let formData = ref({
    isPublished: 1,
    method: 1,
    equityType: 1,
    restriction: 0,
    range: [],
    couponId: []
  })
  let vipList = ref([])
  let range = ref([])
  // 存储从选择页接收的优惠券
  const receivedCoupons = ref([]);
  const uploadedImagesOne = ref([]);
  // 控制提示框显示状态
  const isTooltipShow = ref(false)
  const iconRef = ref(null); // 图标元素
  const tooltipRef = ref(null); // 提示框元素
  const tooltipContainer = ref(null); // 容器元素
  // 点击图标：切换提示框显示/隐藏
  const toggleTooltip = () => {
    isTooltipShow.value = !isTooltipShow.value
    isTooltipShows.value = false
  }
  const isTooltipShows = ref(false)
  const toggleTooltips = () => {
    isTooltipShows.value = !isTooltipShows.value
    isTooltipShow.value = false
  }

  // 全局点击事件处理函数
  const handleClickOutside = (e) => {
    isTooltipShow.value = false
    isTooltipShows.value = false
  };
  onLoad(async (e) => {
    console.log(e, '1111111');
    if (e.spuId) {
      spuId.value = e.spuId;
      tit.value = '编辑会员权益';
      getDetail(e.spuId);
    }

    getList();
  });
  const handleReceiveCoupons = (coupons) => {
    console.log(coupons, '收到选中的优惠券');
    receivedCoupons.value = coupons;
    // 处理表单数据（注意：确保 coupons 里有 a 和 b 字段，对应 id 和 name）
    formData.value.couponName = coupons.map(item => item.b || '').join(',');
    formData.value.couponId = coupons.map(item => item.a || '');
  };

  // 2. 页面挂载时，监听自定义事件（如：receive-selected-coupons）
  onMounted(() => {
    // 绑定事件：事件名自定义，确保和选择页一致
    uni.$on('receive-selected-coupons', handleReceiveCoupons);
  });

  // 3. 页面卸载时，移除事件监听（避免内存泄漏）
  onUnmounted(() => {
    uni.$off('receive-selected-coupons', handleReceiveCoupons);
  });
  const handleUpload = (imageUrl) => {
    console.log("上传成功")
    uploadedImagesOne.value[0] = imageUrl
  };

  // 处理删除事件
  const handleRemove = (removedUrl) => {
    uploadedImagesOne.value = []
  };
  // 选择权益类型
  const changeType = (e) => {
    console.log(e, 'eeeee')
    if (e == 0) {
      equityType.value = true
    } else {
      equityType.value = false
    }
  }
  // 选择日期
  const handleTime = (e) => {
    formData.value.range = e
    // if (e.length > 0) {
    //   pageInfo.startDate = e[0] + ' ' + '00:00:00'
    //   pageInfo.endDate = e[1] + ' ' + '23:59:59'
    // } else {
    //   pageInfo.startDate = undefined
    //   pageInfo.endDate = undefined
    // }
  }
  // 选择优惠券
  const handleCoupon = () => {
    uni.navigateTo({
      url: `/pages/vip/interests/selectCoupon?couponId=${formData.value.couponId}`,
    })
  }

  const getList = async () => {
    let res = await getAttributeDefinitions({
      page: 1,
      limit: 1000,
      status: 1
    })
    vipList.value = res.Result.records || [];
  }
  const getDetail = async (spuId) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    let res = await getBySpuId({
      spuId
    })
    let data = res.Result;
    formData.value.spuId = data.spuId
    formData.value.oldSpuId = data.spuId
    formData.value.name = data.name
    formData.value.name = data.name
    // formData.value.categoryId = data.categoryId
    const targetId = data.categoryId;
    console.log(categoryList.value, 'categoryList.value')
    if (isCategoryIdExist(categoryList.value, targetId)) {
      formData.value.categoryId = targetId;
    } else {
      formData.value.categoryId = undefined
    }
    formData.value.sortOrder = data.sortOrder ? data.sortOrder : ''
    formData.value.sceneLabel = data.sceneLabel
    formData.value.deliveryMethod = data.deliveryMethod
    formData.value.isPublished = data.isPublished
    formData.value.productionTime = data.productionTime ? data.productionTime : ''
    formData.value.retailPrice = data.retailPrice
    formData.value.marketPrice = data.marketPrice
    formData.value.costPrice = data.costPrice
    formData.value.addonKind = data.addonKind
    formData.value.description = data.description
    console.log(data, 'data')
    // 规格
    if (data.specs) {
      isInitializing.value = true;
      specGroups.value = data.specs.map(spec => ({
        specName: spec.name,
        specValues: spec.specValues.map(item => item.value),
        tempValue: ''
      }));
      nextTick(() => {
        isInitializing.value = false;
      });
      console.log(specGroups.value, 'specGroups.value')
    }
    // 笛卡尔积
    if (data.skusList) {
      specsRows.value = data.skusList
      show.value = true
    }

    // 加料
    if (data.addonDtoList) {
      feedingList.value = data.addonDtoList
    }
    // 属性
    if (data.attributeDtoList) {
      attributeList.value = data.attributeDtoList
    }
    if (data?.mainImage) {
      uploadedImagesOne.value[0] = data.mainImage;
    }
    if (data?.introImages) {
      const arr = data.introImages.split(',')
      uploadedImages.value = arr;
    }
    uni.hideLoading()
  }
  const addVIP = (type) => {
    let arr = []
    vipLevelList.value.forEach((item) => {
      arr.push(item.definitionId)
    })
    valuePopup.value = arr
    listPopup.value = JSON.parse(JSON.stringify(vipList.value))
    showPopup.value = true
    titPopup.value = type
  }

  // 商品属性 商品加料 确定
  const surePopup = (type, checkboxData) => {
    showPopup.value = false;
    vipLevelList.value = vipList.value
      .filter(item => checkboxData.includes(item.definitionId)) // 先过滤
      .map(item => JSON.parse(JSON.stringify(item))); // 对每个元素深拷贝
    console.log(vipLevelList.value)
    // vipLevelList.value.map(item => item.name).join(',')
    formData.value.level = vipLevelList.value.map(item => item.name).join(',');
  }
  const cancelPopup = (type) => {
    showPopup.value = false
  }

  const back = () => {}
  const submit = () => {
    let err = '';
    const intReg = /^[1-9]\d*$/;
    const topRequired = [{
        k: 'spuId',
        err: '请输入权益名称'
      },
      {
        k: 'level',
        err: '请选择适用会员等级'
      },
      {
        k: 'sortOrder',
        err: '请输入权益排序',
        validate: (value) => {
          const num = Number(value);
          return Number.isInteger(num) && num >= 0;
        },
        validateErr: '权益排序必须是大于等于0的正整数'
      },
      {
        k: 'description',
        err: '请输入权益描述'
      }
    ];

    for (const item of topRequired) {
      if (!formData.value[item.k] && formData.value[item.k] !== 0) {
        err = item.err
        break
      }
      // 再校验数值合法性（如果有校验规则）
      if (item.validate && !item.validate(formData.value[item.k])) {
        err = item.validateErr
        break
      }
    }
    if (err) {
      uni.showToast({
        title: err,
        duration: 2000,
        icon: 'none'
      });
      return;
    }

    if (!uploadedImagesOne.value?.length) {
      err = '请上传权益图标';
      uni.showToast({
        title: err,
        duration: 2000,
        icon: 'none'
      });
      return;
    }
    const productionTime = String(formData.value.productionTime || '').trim();
    if (equityType.value == true) {
      if (formData.value.couponId.length <= 0) {
        err = '请选择优惠券';
      }
      if (formData.value.range.length <= 0) {
        err = '请选择日期';
      }
      if (productionTime === '') {
        err = '请输入发放次数';
      } else if (!intReg.test(productionTime)) {
        err = '发放次数必须是大于0的正整数';
      }
      if (err) {
        uni.showToast({
          title: err,
          duration: 2000,
          icon: 'none'
        });
        return;
      }
    }

  };
  const submitReq = async () => {

  }
  const close = () => {
    uni.navigateBack()
  }
</script>
<style lang="scss" scoped>
  :deep(.is-disabled) {
    color: #333 !important;
  }

  :deep(.uni-date-x) {
    height: 32px !important;
    line-height: 32px !important;
  }

  .goods-container {
    width: 100%;
    background: #ffffff;
    border-radius: 10px;
    margin: 10px 10px 0;
    display: flex;
    flex-direction: column;
    position: relative;
    z-index: 999999;

    :deep(.uni-date-mask--pc) {
      position: static !important;
    }

    .form-con {
      padding: 0 0px 0 67px;
      box-sizing: border-box;

      .flex-label {
        flex: 1;
      }

      .direction-container {
        display: flex;
        align-items: center;
        margin-left: 8px;

        .item {
          position: relative;

          .tooltip-box {
            width: 160px;
            position: absolute;
            left: 50%;
            top: calc(100% + 6px);
            transform: translateX(-50%);
            background: rgba(47, 75, 153, 0.8);
            font-size: 14px;
            color: #fff;
            padding: 8px;
            box-sizing: border-box;
            border-radius: 6px;
            z-index: 9999;
            display: none;

            &.show {
              display: block;
            }
          }

          .tooltip-arrow {
            position: absolute;
            top: -6px;
            left: 50%;
            transform: translateX(-50%);
            width: 0;
            height: 0;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            border-top: 6px solid rgba(47, 75, 153, 0.8);
            border-bottom: 6px solid rgba(47, 75, 153, 0.8);
            border-top: none;
          }
        }
      }

      .icon-con {
        width: 14px;
        height: 14px;
        vertical-align: middle;
        cursor: pointer;
      }

      // :deep(.u-form-item__body__right__content__slot) {
      //   flex-direction: column !important;
      //   align-items: baseline !important;
      // }

      .suffix-txt {
        background: #f5f6f8;
        border-left: 1px solid #e8ecef;
        font-weight: 400;
        font-size: 14px;
        color: #334681;
        padding: 6px 13px;
        box-sizing: border-box;
      }

      .suffix-num {
        font-weight: 400;
        font-size: 14px;
        color: rgba(51, 70, 129, 0.6);
        padding-right: 5px;
        box-sizing: border-box;
      }

      :deep(.u-button) {
        height: 32px;
        width: 100px;
        margin-left: 10px;
      }
    }

    .info-tit {
      font-weight: 500;
      font-size: 14px;
      color: #333333;
      line-height: 20px;
      padding-left: 37px;
      box-sizing: border-box;
      margin: 25px 0 10px;
    }
  }
</style>
